/**
 * API 服务模块 - 提供模拟数据和API请求
 */
const API = {
    // 基本配置
    baseUrl: 'http://localhost:8080/api/v1',  // 相对路径，避免跨域问题
    useMock: false,  // 是否使用模拟数据，可以设置为true进行开发调试
    
    // 设备ID缓存
    _deviceId: null,
    
    // 获取设备ID
    getDeviceId() {
        if (!this._deviceId) {
            this._deviceId = localStorage.getItem('device_id');
            if (!this._deviceId) {
                this._deviceId = this.mockData.generateUUID();
                localStorage.setItem('device_id', this._deviceId);
            }
        }
        return this._deviceId;
    },
    
    // 请求封装 - 优化版本，使用缓存提高性能
    _cache: {},
    _pendingRequests: {},
    
    async request(endpoint, options = {}) {
        try {
            // 如果是GET请求且没有禁用缓存，检查缓存
            const useCache = options.method !== 'POST' && 
                             options.method !== 'PUT' && 
                             options.method !== 'DELETE' && 
                             !options.noCache;
            
            const cacheKey = `${endpoint}_${JSON.stringify(options)}`;
            
            // 如果有相同请求正在进行中，复用同一个promise
            if (this._pendingRequests[cacheKey]) {
                return this._pendingRequests[cacheKey];
            }
            
            // 检查缓存
            if (useCache && this._cache[cacheKey]) {
                const cachedData = this._cache[cacheKey];
                const now = Date.now();
                
                // 缓存10分钟
                if (now - cachedData.timestamp < 10 * 60 * 1000) {
                    return cachedData.data;
                }
                
                // 缓存过期，删除
                delete this._cache[cacheKey];
            }
            
            const url = `${this.baseUrl}${endpoint}`;
            const headers = {
                ...options.headers
            };
            
            // 只在非FormData请求时添加Content-Type
            if (!(options.body instanceof FormData)) {
                headers['Content-Type'] = 'application/json';
            }
            
            // 添加设备ID头
            headers['X-Device-ID'] = this.getDeviceId();
            
            // 创建请求Promise并保存到pendingRequests
            const requestPromise = (async () => {
                const response = await fetch(url, {
                    ...options,
                    headers
                });
                
                // 处理非2xx响应
                if (!response.ok) {
                    const error = await response.json().catch(() => ({ message: 'Network Error' }));
                    throw new Error(error.message || `HTTP error: ${response.status}`);
                }
                
                const result = await response.json();
                
                // 如果是GET请求，缓存结果
                if (useCache) {
                    this._cache[cacheKey] = {
                        data: result,
                        timestamp: Date.now()
                    };
                }
                
                return result;
            })();
            
            this._pendingRequests[cacheKey] = requestPromise;
            
            try {
                return await requestPromise;
            } finally {
                // 请求完成后，删除pendingRequests中的记录
                delete this._pendingRequests[cacheKey];
            }
        } catch (error) {
            console.error(`API请求错误 [${endpoint}]:`, error);
            // 如果启用了模拟数据，在API失败时回退到模拟数据
            if (this.useMock) {
                console.warn(`尝试使用模拟数据作为回退...`);
                return this.mockFallback(endpoint, options);
            }
            throw error;
        }
    },
    
    // 清除缓存
    clearCache() {
        this._cache = {};
    },
    
    // 延迟函数，模拟网络请求 - 使用共享实现减少代码量
    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    },
    
    // 初始化API - 预加载重要数据
    async init() {
        // 初始化设备ID，调用getDeviceId就会设置
        this.getDeviceId();
        
        // 初始化模拟数据
        if (this.useMock) {
            await this.mockData.init();
        }
        
        // 预加载分类数据
        try {
            this.getCategories();
        } catch (e) {
            console.warn("预加载分类数据失败");
        }
        
        console.log('API 服务初始化完成，模式:', this.useMock ? '模拟数据' : '真实API');
    },
    
    // 模拟数据回退
    async mockFallback(endpoint, options) {
        // 根据endpoint返回相应的模拟数据
        const path = endpoint.split('?')[0];
        
        if (path.startsWith('/wallpapers')) {
            if (path.includes('/search')) {
                const searchQuery = new URLSearchParams(endpoint.split('?')[1]).get('keyword');
                return this.mockSearchWallpapers(searchQuery);
            } else if (path.includes('/random')) {
                return this.mockGetRandomWallpaper();
            } else if (path.match(/\/\d+$/)) {
                const id = path.split('/').pop();
                return this.mockGetWallpaperDetail(id);
            } else {
                return this.mockGetWallpapers();
            }
        } else if (path.startsWith('/categories')) {
            return this.mockGetCategories();
        } else if (path.startsWith('/favorites')) {
            return this.mockGetFavorites();
        } else if (path.startsWith('/downloads')) {
            // 处理下载相关逻辑
            return { data: { success: true } };
        }
        
        throw new Error('未找到匹配的模拟数据');
    },
    
    // 模拟数据 - 实际项目中替换为真实API调用
    mockData: {
        deviceId: null, // 设备ID将在初始化时生成或从localStorage获取
        
        // 分类数据
        categories: [
            { id: 'nature', name: '自然风光', image: 'https://images.unsplash.com/photo-1501854140801-50d01698950b?w=500', wallpaper_count: 320 },
            { id: 'city', name: '城市建筑', image: 'https://images.unsplash.com/photo-1519501025264-65ba15a82390?w=500', wallpaper_count: 275 },
            { id: 'abstract', name: '抽象艺术', image: 'https://images.unsplash.com/photo-1541701494587-cb58502866ab?w=500', wallpaper_count: 198 },
            { id: 'minimal', name: '简约风格', image: 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=500', wallpaper_count: 145 },
            { id: 'dark', name: '暗色系', image: 'https://images.unsplash.com/photo-1478760329108-5c3ed9d495a0?w=500', wallpaper_count: 167 },
            { id: 'bright', name: '亮色系', image: 'https://images.unsplash.com/photo-1419242902214-272b3f66ee7a?w=500', wallpaper_count: 210 }
        ],
        
        // 生成模拟壁纸数据的函数
        generateWallpapers(count = 20, category = null) {
            const wallpapers = [];
            const categories = ['nature', 'city', 'abstract', 'minimal', 'dark', 'bright'];
            const tagsByCategory = {
                nature: ['山', '水', '树', '绿色', '自然', '海洋', '风景', '云彩'],
                city: ['建筑', '城市', '街道', '灯光', '夜景', '摩天楼', '桥梁'],
                abstract: ['几何', '渐变', '图案', '流体', '多彩', '波浪', '曲线'],
                minimal: ['简约', '白色', '线条', '空间', '黑白', '极简', '留白'],
                dark: ['黑色', '灰色', '夜间', '神秘', '深色', '月亮', '星空'],
                bright: ['阳光', '明亮', '彩色', '活力', '鲜艳', '黄色', '橙色']
            };
            
            for (let i = 0; i < count; i++) {
                const id = this.generateUUID();
                const cat = category || categories[Math.floor(Math.random() * categories.length)];
                const width = 1080;
                const height = 1920;
                const date = new Date();
                date.setDate(date.getDate() - Math.floor(Math.random() * 30));
                
                // 使用Unsplash获取随机图片，每次生成不同的
                const wallpaper = {
                    id,
                    url: `https://source.unsplash.com/random/${width}x${height}?${cat}&sig=${id}`,
                    thumbnail_url: `https://source.unsplash.com/random/300x400?${cat}&sig=${id}`,
                    preview_url: `https://source.unsplash.com/random/500x800?${cat}&sig=${id}`,
                    category: cat,
                    tags: this.getRandomSubset(tagsByCategory[cat], Math.floor(Math.random() * 3) + 2),
                    width,
                    height,
                    created_at: date.toISOString(),
                    downloads: Math.floor(Math.random() * 2000)
                };
                
                wallpapers.push(wallpaper);
            }
            
            return wallpapers;
        },
        
        // 获取壁纸详情数据
        getWallpaperDetail(id) {
            const wallpaper = this.wallpapers.find(w => w.id === id);
            if (!wallpaper) return null;
            
            // 克隆基本信息，添加详情所需的额外字段
            const detail = { ...wallpaper };
            detail.description = '这是一幅精美的壁纸，由摄影师精心拍摄，展现了令人惊叹的画面。适合手机桌面使用，给您带来视觉享受。';
            detail.author = '摄影师小明';
            detail.author_link = 'https://rufeng-wallpaper.com/authors/xiaoming';
            detail.is_premium = Math.random() > 0.7;
            
            // 相关壁纸 - 获取3张同类别的壁纸
            detail.related_wallpapers = this.wallpapers
                .filter(w => w.category === wallpaper.category && w.id !== id)
                .slice(0, 3);
            
            return detail;
        },
        
        // 生成UUID模拟ID
        generateUUID() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        },
        
        // 从数组中随机选择n个元素
        getRandomSubset(array, n) {
            const shuffled = array.sort(() => 0.5 - Math.random());
            return shuffled.slice(0, n);
        },
        
        // 初始化模拟数据
        init() {
            // 检查是否已有设备ID，没有则创建
            this.deviceId = localStorage.getItem('device_id');
            if (!this.deviceId) {
                this.deviceId = this.generateUUID();
                localStorage.setItem('device_id', this.deviceId);
            }
            
            // 初始化壁纸数据
            this.wallpapers = this.generateWallpapers(40);
            
            // 初始化收藏数据
            this.favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
            
            console.log('API 模拟数据初始化完成');
        }
    },
    
    // 模拟API实现
    async mockGetWallpapers(params = {}) {
        await this.delay(800);
        
        const { page = 1, limit = 10, category = null, sort = 'popular' } = params;
        
        // 筛选分类
        let wallpapers = category
            ? this.mockData.wallpapers.filter(w => w.category === category)
            : [...this.mockData.wallpapers];
        
        // 排序
        if (sort === 'newest') {
            wallpapers.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
        } else if (sort === 'popular') {
            wallpapers.sort((a, b) => b.downloads - a.downloads);
        } else if (sort === 'trending') {
            // 模拟趋势排序
            wallpapers.sort((a, b) => {
                const scoreA = b.downloads * 0.7 + new Date(b.created_at).getTime() * 0.3;
                const scoreB = a.downloads * 0.7 + new Date(a.created_at).getTime() * 0.3;
                return scoreA - scoreB;
            });
        }
        
        // 分页
        const startIndex = (page - 1) * limit;
        const endIndex = startIndex + limit;
        const paginatedWallpapers = wallpapers.slice(startIndex, endIndex);
        
        // 模拟API响应数据结构
        return {
            data: paginatedWallpapers,
            pagination: {
                current_page: page,
                total_pages: Math.ceil(wallpapers.length / limit),
                total_items: wallpapers.length,
                items_per_page: limit
            }
        };
    },
    
    async mockSearchWallpapers(query, page = 1, limit = 10) {
        await this.delay(800);
        
        // 简单模拟搜索功能
        const searchResults = this.mockData.wallpapers.filter(wallpaper => {
            // 在标签和分类中搜索
            const tagsMatch = wallpaper.tags.some(tag => tag.includes(query));
            const categoryMatch = wallpaper.category.includes(query);
            return tagsMatch || categoryMatch;
        });
        
        // 分页
        const startIndex = (page - 1) * limit;
        const endIndex = startIndex + limit;
        const paginatedResults = searchResults.slice(startIndex, endIndex);
        
        return {
            data: paginatedResults,
            pagination: {
                current_page: page,
                total_pages: Math.ceil(searchResults.length / limit),
                total_items: searchResults.length,
                items_per_page: limit
            }
        };
    },
    
    async mockGetWallpaperDetail(id) {
        await this.delay(500);
        
        const detail = this.mockData.getWallpaperDetail(id);
        if (!detail) {
            throw new Error('未找到该壁纸');
        }
        
        return { data: detail };
    },
    
    async mockGetRandomWallpaper(category = null) {
        await this.delay(300);
        
        // 筛选分类
        let wallpapers = category
            ? this.mockData.wallpapers.filter(w => w.category === category)
            : this.mockData.wallpapers;
        
        // 随机选择一张
        const randomIndex = Math.floor(Math.random() * wallpapers.length);
        const randomWallpaper = wallpapers[randomIndex];
        
        return { data: randomWallpaper };
    },
    
    async mockGetCategories() {
        await this.delay(300);
        
        return { data: this.mockData.categories };
    },
    
    async mockGetFavorites(page = 1, limit = 10) {
        await this.delay(500);
        
        const favoriteIds = this.mockData.favorites;
        const favoriteWallpapers = this.mockData.wallpapers.filter(w => favoriteIds.includes(w.id));
        
        // 分页
        const startIndex = (page - 1) * limit;
        const endIndex = startIndex + limit;
        const paginatedFavorites = favoriteWallpapers.slice(startIndex, endIndex);
        
        return {
            data: paginatedFavorites,
            pagination: {
                current_page: page,
                total_pages: Math.ceil(favoriteWallpapers.length / limit),
                total_items: favoriteWallpapers.length,
                items_per_page: limit
            }
        };
    },
    
    // 实际API实现
    // 获取壁纸列表
    async getWallpapers(params = {}) {
        const { page = 1, limit = 10, category = null, sort = 'popular' } = params;
        let url = `/wallpapers?page=${page}&limit=${limit}`;
        
        if (category) url += `&category=${category}`;
        if (sort) url += `&sort=${sort}`;
        
        if (this.useMock) {
            return this.mockGetWallpapers(params);
        }
        
        try {
            return await this.request(url);
        } catch (error) {
            console.error('获取壁纸列表失败:', error);
            return this.mockGetWallpapers(params);
        }
    },
    
    // 搜索壁纸
    async searchWallpapers(keyword, page = 1, limit = 10) {
        const url = `/wallpapers/search?keyword=${encodeURIComponent(keyword)}&page=${page}&limit=${limit}`;
        
        if (this.useMock) {
            return this.mockSearchWallpapers(keyword, page, limit);
        }
        
        try {
            return await this.request(url);
        } catch (error) {
            console.error('搜索壁纸失败:', error);
            return this.mockSearchWallpapers(keyword, page, limit);
        }
    },
    
    // 获取壁纸图片URL
    getWallpaperImageUrl(id) {
        return `${this.baseUrl}/wallpapers/image/${id}`;
    },

    // 获取壁纸图片URL
    getWallpaperDownloadUrl(id) {
        return `${this.baseUrl}/wallpapers/download/${id}`;
    },

    // 获取壁纸缩略图URL
    getWallpaperThumbnailUrl(id) {
        return `${this.baseUrl}/wallpapers/thumbnail/${id}`;
    },

    // 获取壁纸详情
    async getWallpaperDetail(id) {
        if (this.useMock) {
            return this.mockGetWallpaperDetail(id);
        }
        
        try {
            return await this.request(`/wallpapers/${id}`);
        } catch (error) {
            console.error('获取壁纸详情失败:', error);
            return this.mockGetWallpaperDetail(id);
        }
    },
    
    // 获取随机壁纸
    async getRandomWallpaper(category = null) {
        let url = '/wallpapers/random';
        if (category) url += `?category=${category}`;
        
        if (this.useMock) {
            return this.mockGetRandomWallpaper(category);
        }
        
        try {
            return await this.request(url);
        } catch (error) {
            console.error('获取随机壁纸失败:', error);
            return this.mockGetRandomWallpaper(category);
        }
    },
    
    // 获取所有分类
    async getCategories() {
        if (this.useMock) {
            return this.mockGetCategories();
        }
        
        try {
            return await this.request('/categories');
        } catch (error) {
            console.error('获取分类失败:', error);
            return this.mockGetCategories();
        }
    },
    
    // 获取收藏列表
    async getFavorites(page = 1, limit = 10) {
        const url = `/favorites?page=${page}&limit=${limit}`;
        
        if (this.useMock) {
            return this.mockGetFavorites(page, limit);
        }
        
        try {
            return await this.request(url);
        } catch (error) {
            console.error('获取收藏列表失败:', error);
            return this.mockGetFavorites(page, limit);
        }
    },
    
    // 添加到收藏
    async addToFavorites(wallpaperId) {
        if (this.useMock) {
            await this.delay(300);
            
            // 检查是否已收藏
            if (this.mockData.favorites.includes(wallpaperId)) {
                return { message: '已经收藏过该壁纸' };
            }
            
            // 添加到收藏
            this.mockData.favorites.push(wallpaperId);
            
            // 更新本地存储
            localStorage.setItem('favorites', JSON.stringify(this.mockData.favorites));
            
            return { message: '壁纸已添加到收藏' };
        }
        
        try {
            return await this.request(`/favorites/${wallpaperId}`, {
                method: 'POST'
            });
        } catch (error) {
            console.error('添加收藏失败:', error);
            // 回退到本地模拟
            if (this.mockData.favorites.includes(wallpaperId)) {
                return { message: '已经收藏过该壁纸' };
            }
            this.mockData.favorites.push(wallpaperId);
            localStorage.setItem('favorites', JSON.stringify(this.mockData.favorites));
            return { message: '壁纸已添加到收藏' };
        }
    },
    
    // 从收藏中移除
    async removeFromFavorites(wallpaperId) {
        if (this.useMock) {
            await this.delay(300);
            
            // 检查是否已收藏
            const index = this.mockData.favorites.indexOf(wallpaperId);
            if (index === -1) {
                throw new Error('收藏中不存在该壁纸');
            }
            
            // 从收藏中移除
            this.mockData.favorites.splice(index, 1);
            
            // 更新本地存储
            localStorage.setItem('favorites', JSON.stringify(this.mockData.favorites));
            
            return { message: '壁纸已从收藏中移除' };
        }
        
        try {
            return await this.request(`/favorites/${wallpaperId}`, {
                method: 'DELETE'
            });
        } catch (error) {
            console.error('移除收藏失败:', error);
            // 回退到本地模拟
            const index = this.mockData.favorites.indexOf(wallpaperId);
            if (index !== -1) {
                this.mockData.favorites.splice(index, 1);
                localStorage.setItem('favorites', JSON.stringify(this.mockData.favorites));
            }
            return { message: '壁纸已从收藏中移除' };
        }
    },
    
    // 检查是否已收藏
    async checkFavorite(wallpaperId) {
        if (this.useMock) {
            await this.delay(100);
            
            const isFavorite = this.mockData.favorites.includes(wallpaperId);
            
            return { is_favorite: isFavorite };
        }
        
        try {
            return await this.request(`/favorites/check/${wallpaperId}`);
        } catch (error) {
            console.error('检查收藏状态失败:', error);
            return { is_favorite: this.mockData.favorites.includes(wallpaperId) };
        }
    },
    
    // 下载壁纸
    async downloadWallpaper(wallpaperId, quality = 'high') {
        if (this.useMock) {
            await this.delay(500);
            
            const wallpaper = this.mockData.wallpapers.find(w => w.id === wallpaperId);
            if (!wallpaper) {
                throw new Error('未找到该壁纸');
            }
            
            return { download_url: wallpaper.url };
        }
        
        try {
            //获取下载URL
            return await this.request(`/wallpapers/${wallpaperId}/download?quality=${quality}`, {
                method: 'POST'
            });
        } catch (error) {
            console.error('下载壁纸失败:', error);
            // 回退到模拟数据
            const wallpaper = this.mockData.wallpapers.find(w => w.id === wallpaperId);
            return { download_url: wallpaper?.url || '' };
        }
    },

    /**
     * 上传壁纸
     * @param {FormData} formData - 包含壁纸信息的FormData对象
     * @param {Function} onProgress - 上传进度回调函数
     * @returns {Promise} 上传结果
     */
    uploadWallpaper: async (formData, onProgress) => {
        if (API.useMock) {
            // 模拟上传延迟
            await new Promise(resolve => setTimeout(resolve, 2000));
            return {
                success: true,
                data: {
                    id: Math.floor(Math.random() * 1000),
                    title: formData.get('title'),
                    description: formData.get('description'),
                    categoryId: formData.get('categoryId'),
                    tags: formData.get('tags').split(','),
                    imageUrl: 'https://source.unsplash.com/random/1920x1080',
                    thumbnailUrl: 'https://source.unsplash.com/random/400x300',
                    downloads: 0,
                    favorites: 0,
                    createTime: new Date().toISOString()
                }
            };
        }

        try {
            const response = await fetch(`${API.baseUrl}/api/wallpapers/upload`, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Device-ID': API.getDeviceId()
                },
                onUploadProgress: (progressEvent) => {
                    if (onProgress) {
                        const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                        onProgress(progress);
                    }
                }
            });

            if (!response.ok) {
                throw new Error('Upload failed');
            }

            return await response.json();
        } catch (error) {
            console.error('Upload error:', error);
            throw error;
        }
    },

    // 上传壁纸
    async uploadWallpaper(formData, onProgress) {
        try {
            const url = `${this.baseUrl}/wallpapers/upload`;
            const headers = {
                'X-Device-ID': this.getDeviceId()
            };

            // 使用XMLHttpRequest来支持上传进度
            return new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest();

                xhr.upload.addEventListener('progress', (event) => {
                    if (event.lengthComputable && onProgress) {
                        const percentComplete = Math.round((event.loaded / event.total) * 100);
                        onProgress(percentComplete);
                    }
                });

                xhr.addEventListener('load', () => {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        try {
                            const response = JSON.parse(xhr.responseText);
                            resolve(response);
                        } catch (error) {
                            reject(new Error('解析响应失败'));
                        }
                    } else {
                        try {
                            const error = JSON.parse(xhr.responseText);
                            reject(new Error(error.message || '上传失败'));
                        } catch (error) {
                            reject(new Error(`上传失败: ${xhr.status}`));
                        }
                    }
                });

                xhr.addEventListener('error', () => {
                    reject(new Error('网络错误'));
                });

                xhr.addEventListener('abort', () => {
                    reject(new Error('上传已取消'));
                });

                xhr.open('POST', url, true);
                Object.entries(headers).forEach(([key, value]) => {
                    xhr.setRequestHeader(key, value);
                });
                xhr.send(formData);
            });
        } catch (error) {
            console.error('上传壁纸失败:', error);
            throw error;
        }
    }
};

// 页面加载完成后初始化API
document.addEventListener('DOMContentLoaded', () => {
    API.init();
}); 